package com.avertymaroc.users;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Window;
import com.avertymaroc.app.MainActivity;
import com.avertymaroc.app.R;
import com.avertymaroc.beans.User;
import com.avertymaroc.library.AlertDialogue;
import com.avertymaroc.library.ConnectionDetector;
import com.avertymaroc.library.C;
import com.avertymaroc.library.GrideAdapter;
import com.avertymaroc.library.HttpManager;
import com.avertymaroc.library.SessionManager;

public class HomeActivity extends SherlockActivity  {

	private static final int MON_COMPTE		 = 0;
	private static final int SONDAGE_RAPIDE  = 1;
	private static final int CREER_SONDAGE	 = 2;
	private static final int SONDAGE_PUBLIC  = 3;
	private static final int RESULTAT_SONPUB = 4;
	private static final int SONDAGE_PRIVE	 = 5;
	private TextView userInfo;
	private ImageView barConversion;
	private ImageButton logOut;
	private ImageButton video_about;
	boolean flag = true;
	Listener listener;
	TextView video_about_titre ;
	ConnectionDetector connexionDeetector;

	private ImageButton sond_prive, sond_pub, sond_rap, new_sr, conversion;
	private GridView gridView = null ;
	private ImageView image_convert;
	ArrayList<HashMap<String, Object>> data = null ;
	private GrideAdapter mAdapter;
	private LinearLayout convert;
	

	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(MainActivity.THEME);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		init();
	}


	 
	    @Override
	    public boolean onContextItemSelected(android.view.MenuItem item) {
	        //Note how this callback is using the fully-qualified class name
	        Toast.makeText(this, "Got click: " + item.getOrder(), Toast.LENGTH_SHORT).show();
	        return true;
	    }
	
	@Override
	protected void onResume() {
		super.onResume();
		boolean isLogIn = new SessionManager(getApplicationContext())
				.isLoggedIn();
		if (!isLogIn) {
			// After logout redirect user to Loing Activity
			Intent i = new Intent(getApplicationContext(), MainActivity.class);
			// Closing all the Activities
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

			// Add new Flag to start new Activity
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(i);
			finish();
		}
		
	}
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		if(flag){
			flag = false;
		ImageView bar_noir = (ImageView) findViewById(R.id.bar_noir);
		barConversion = (ImageView) findViewById(R.id.bar_conversion);
		
		int points = new SessionManager(getApplicationContext()).getUserDetails().getPoint();
		
		Double percent =  (points + 0.0) /1000.0;
		
		int bn_w = bar_noir.getWidth();
		barConversion.getLayoutParams().width = (int) (percent *  bn_w);
		}
		
		
	}

	private class Listener implements  OnItemClickListener, OnClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
		if( !connexionDeetector.isConnectingToInternet() ){
			AlertDialogue.afficher(HomeActivity.this , R.string.no_connexion_detected);
		}
		else{
			
			Intent i;
			switch(position){
			case MON_COMPTE:
				getProfilInfos();
				break;
			case SONDAGE_RAPIDE :
				
				i = new Intent(HomeActivity.this, SondagesRapides.class);
				startActivity(i);
				break;
			case CREER_SONDAGE :
				i = new Intent(HomeActivity.this , AddSondRap.class);
				startActivity(i);
				break;
			case SONDAGE_PUBLIC :
				
//				Uri uri = Uri.parse( C.site_url()  );
//				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//				startActivity(intent);
				 i = new Intent(HomeActivity.this , Sondage_public.class );
				 startActivity(i);
				
				
				break;
			case RESULTAT_SONPUB :
				i = new Intent(HomeActivity.this , Articles.class);
				startActivity(i);
				break;
			case SONDAGE_PRIVE :

				i = new Intent(HomeActivity.this , Sondage_prive.class);
				startActivity(i);
				
			break;	
			}
		}
			
		}

		@Override
		public void onClick(View v) {
			if(v == logOut){
				new SessionManager(getApplicationContext()).logoutUser();
				return;
			}
			if( v == image_convert || v == convert )
			{
				Intent intent = new Intent(getApplication() , Conversion.class);
				startActivity(intent);
			}
			if(v == video_about || v == video_about_titre){
				Intent intent = new Intent(HomeActivity.this, VideosPlayer.class);
				startActivity(intent);

			}
			
			
		}

	}
	
	

	
	
	

	
	
	private void init(){
		
		listener 				= new Listener();
		gridView 				= (GridView) findViewById(R.id.grid_view_home);
		data 					= new ArrayList<HashMap<String,Object>>();
		logOut 					= (ImageButton)findViewById(R.id.ab_right_button);
		connexionDeetector 		= new ConnectionDetector(getApplicationContext());
		convert 				= (LinearLayout) findViewById(R.id.conversion);
		image_convert 			= (ImageView) findViewById(R.id.image_convert);
		video_about				= (ImageButton) findViewById(R.id.video_about);
		video_about_titre		= (TextView) findViewById(R.id.video_about_titre);
		
		
		findViewById(R.id.ab_left_button).setVisibility(Button.INVISIBLE);
		logOut.setOnClickListener(listener);
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		map.put(C.ICON_BTN_ID , R.drawable.mon_compte);
		map.put(C.TITRE_BTN , getResources().getString(R.string.mon_compte));
		data.add(map);
		
		map = new HashMap<String, Object>();
		map.put(C.ICON_BTN_ID , R.drawable.sondage_rapide);
		map.put(C.TITRE_BTN , getResources().getString(R.string.sondages_rapides));
		data.add(map);
		
		map = new HashMap<String, Object>();
		map.put(C.ICON_BTN_ID , R.drawable.add_sondage);
		map.put(C.TITRE_BTN , getResources().getString(R.string.creer_sr));
		data.add(map);
		
		map = new HashMap<String, Object>();
		map.put(C.ICON_BTN_ID , R.drawable.sondage_public);
		map.put(C.TITRE_BTN , getResources().getString(R.string.sondages_public));
		data.add(map);
		
		map = new HashMap<String, Object>();
		map.put(C.ICON_BTN_ID , R.drawable.resultats_sondage);
		map.put(C.TITRE_BTN , getResources().getString(R.string.result_sondage));
		data.add(map);
		
		map = new HashMap<String, Object>();
		map.put(C.ICON_BTN_ID , R.drawable.sondage_prive);
		map.put(C.TITRE_BTN , getResources().getString(R.string.sondages_prives));
		data.add(map);
		
		mAdapter = new GrideAdapter(this, data);
		mAdapter.setType(GrideAdapter.IMAGE);
		gridView.setAdapter(mAdapter);
		
		Listener l =new Listener();
		gridView.setOnItemClickListener(l);
		convert.setOnClickListener(l);
		image_convert.setOnClickListener(l);
		video_about.setOnClickListener(l);
		video_about_titre.setOnClickListener(l);
		userInfo = (TextView) findViewById(R.id.user_infos);
		
		User user = new SessionManager(getApplicationContext())
				.getUserDetails();
		userInfo.setText(userInfo.getText().toString() + " " + user.getPrenom()
				+ ", " + user.getPoint() + " Pts.");

	}

	private void getProfilInfos(){
		
		
		HttpManager profil = new  HttpManager(this) {
			
			@Override
			protected void onPostExecute(String file_url) {
				getpDialog().dismiss();
				JSONObject res = getResult();
				int succes;
				try {
					succes = res.getInt(C.TAG_SUCCESS);
					if(succes == 1){
						Intent i = new Intent(HomeActivity.this  ,Profil.class);
						
						
						i.putExtra(User.KEY_PRENOM, res.getString(User.KEY_PRENOM));
						i.putExtra(User.KEY_NOM , res.getString(User.KEY_NOM ) );
						i.putExtra(User.KEY_EMAIL, res.getString(User.KEY_EMAIL ));
						i.putExtra(User.KEY_TEL, res.getString(User.KEY_TEL));
						i.putExtra(User.KEY_ADRESSE, res.getString(User.KEY_ADRESSE));
						i.putExtra(User.KEY_VILLE, res.getInt(User.KEY_VILLE) );
						i.putExtra(User.KEY_PROFESSION , res.getInt(User.KEY_PROFESSION) );
						i.putExtra(User.KEY_ANNE, res.getInt(User.KEY_ANNE));
						
						startActivity(i);
					}
				} catch (JSONException e) {
					Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
				}
				
			}
		};
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(User.KEY_ID, new SessionManager(this).getUserDetails().getId()+"");
		
		profil.setUrl(C.site_url("mobile/profil/index") )
				.setParams(params)
				.execute();
		
	}




}
